package cloud.keveri.chat4j.provider.chatgpt.listener;

import cloud.keveri.chat4j.provider.chatgpt.model.ChatChoice;
import cloud.keveri.chat4j.provider.chatgpt.model.ChatgptCompletionResponse;
import cloud.keveri.chat4j.api.AbstractEventSourceListener;
import cloud.keveri.chat4j.api.entity.Role;
import cloud.keveri.chat4j.api.entity.chat.Message;
import com.alibaba.fastjson2.JSON;
import okhttp3.sse.EventSource;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nullable;

import java.util.List;

import static cloud.keveri.chat4j.provider.chatgpt.config.Const.Stop_Sign;


/**
 * 借鉴自  <a href="https://gitee.com/grt1228/chatgpt-java">chatgpt-java<a/>
 * <p>
 * 作者：沈自在
 **/
public abstract class AbstractChatgptEventSourceListenerAdapter extends AbstractEventSourceListener {


    @Override
    public void onEvent(@Nullable EventSource eventSource,
                        @Nullable String id, @Nullable String type, @Nullable String data) {

        // 2. 解析响应
        ChatgptCompletionResponse gptResponse = JSON.parseObject(data, ChatgptCompletionResponse.class);
        assert gptResponse != null;

        List<ChatChoice> choices = gptResponse.getChoices();
        if (null == choices || choices.isEmpty()) {
            return;
        }

        // 3. 处理信息
        for (ChatChoice choice : choices) {
            Message delta = choice.getDelta();
            if (Role.ASSISTANT.getValue().equals(delta.getRole())) continue;

            String finishReason = choice.getFinishReason();
            if (StringUtils.isNoneBlank(finishReason) && Stop_Sign.equals(finishReason)) {
                onComplete();
                break;
            }
            onMessage(delta);
        }

    }


    protected abstract void onMessage(Message delta);

    protected abstract void onComplete();
}
